<template>
    <view class="d-kuan">
        <uv-overlay :show="fujian_data_show" @tap="fujian_close_get" zIndex="998" opacity="0.5">
        <view class="warp_fujian">
            <view class="rect_fujian" @tap.stop.prevent>
                <view class="d-kuan ">
                    <view class="d-kuan d-zhuangtai d-fujian-gao">
                        <view class="d-kuan d-zhuangtai-left">
                            <uv-cell icon="download" title="附件详情"></uv-cell>
                        </view>
                        <!--展示循环的附件列表-->
                        <view v-for="(item, index) in fujian_data_add.fujian" :key="index">
                            <uv-cell :icon="item.icon">
                                <template v-slot:title>
                                    <input 
                                        type="text" 
                                        v-model="item.title" 
                                        class="fujian-title-input" 
                                        placeholder="请输入附件标题"
                                        @blur="updateFujianTitle(index, item.title)"
                                    />
                                </template>
                                <template v-slot:value>
                                    <uv-icon name="download" @click="downloadFile(item)" class="d-zuo-10"></uv-icon>
									<uv-icon name="trash" @click="delete_fujian(index)" class="d-zuo-10"></uv-icon>
                                </template>
                            </uv-cell>
                        </view>
                       
                        <view class="d-kuan d-clear"></view>
                        <view class="d-kuan d-shang-10" style="display: flex; justify-content: center; align-items: center;">
                            <uv-upload
                            	:fileList="fileList_fujian1"
                            	name="1"
                            	multiple
                            	leixing="4"
                            	:maxCount="9"
                            	@afterRead="afterRead_fujian"
                            	@delete="delete_fujian"
                            	:xianshi="4"
                            	:previewFullImage="true"
                            	width="50"
                            	height="50"
								accept="all"
                            	fileType="all"
                            ></uv-upload>
                        </view>
                        <uv-button v-if="fujian_data_add && fujian_data_add.fujian && fujian_data_add.fujian.length > 0" class="d-shang-10" type="primary" text="上传确认" @click="postfujian_data_xiugai_api"></uv-button>
                        <uv-button v-else class="d-shang-10 " type="primary" text="添加附件" @click="postfujian_data_xiugai_api" ></uv-button>
                        
                    </view>
                </view>
            </view>
        </view>
    </uv-overlay>
    </view>
</template>

<script>
    import Api from '@/utils/api.js';
    import QuanApi from '@/utils/quan_api.js';
    import NlAudioPlayer from '@/uni_modules/nl-audio-player/components/nl-audio-player/nl-audio-player.vue'
	import { getRequest,postRequest } from '@/utils/wxRequest.js';
export default {
    props: {
        fujian_data_show: {
            type: Boolean,
            default: false
        },
        fujian_data_list: {
            type: [Array, Object], // 支持数组或对象类型
            default: () => []
        },
        tieid: {
            type: [String, Number],
            default: 0
        },
        quanid: {
            type: [String, Number], // 支持字符串或数字类型
            default: 0
        },
    },
    components: {
        NlAudioPlayer
    },
	data() {
		return {
			fujian_data_add:{},
			fujian_data_list_cuozuo: 0,
			fabuid:{},//发布id
            fileList1: [],//附件存储
            fileList_fujian1: [],//附件存储
            fabuid_fujian:{},//发布id
            up_fujian:[],
		}
	},
	watch: {
		// 监听fujian_data_list变化，有数据时传递给fujian_data_add并更新操作状态
		fujian_data_list: {
				handler(newVal) {
					//console.log('fujian_data_list变化:', newVal);
					if (newVal && newVal.length > 0) {
						// 深拷贝数据到fujian_data_add
						var list = JSON.parse(JSON.stringify(newVal[0]));
                        //console.log('传入数据:',list);
                    this.fujian_data_add = list;
                    //console.log('fujian_data_add更新后:', this.fujian_data_add);
                    // 有数据时设置操作为修改模式
                    this.fujian_data_list_cuozuo = 1;
					} else {
						//console.log('fujian_data_list为空');
						// 没有数据时设置操作为添加模式
                    this.fujian_data_list_cuozuo = 0;
					}
				},
				deep: true,
				immediate: true // 立即执行一次
			},
		// 监听弹出组件显示，触发获取发布ID和数据同步
		fujian_data_show: {
				handler(newVal) {
					//console.log('fujian_data_show变化:', newVal);
					if (newVal) {
						this.getFabuid_api();
						// 组件显示时，再次同步数据
						this.syncfujianData();
					}
				},
				immediate: false
			}
	},
	methods: {
		// 附件列表
		fujian_data_cunzai_api(){
			this.$refs.Dfujian_data.fujian_data_cunzai_api();
		},
		// 同步附件数据
		syncfujianData() {
			//console.log('开始同步附件数据');
			//console.log('当前fujian_data_list:', this.fujian_data_list);
			if (this.fujian_data_list) {
				// 深拷贝数据到fujian_data_add
				var list = JSON.parse(JSON.stringify(this.fujian_data_list));
				//console.log('同步的附件数据:', list);
				this.fujian_data_add = list;
				//console.log('同步后fujian_data_add:', this.fujian_data_add);
				// 设置为修改模式
				this.fujian_data_list_cuozuo = 1;
				
				// 同步fileList_fujian1数据为当前已有的fujian_data_list
				if (this.fujian_data_add && this.fujian_data_add.fujian && Array.isArray(this.fujian_data_add.fujian)) {
					this.fileList_fujian1 = this.fujian_data_add.fujian.map((item, index) => ({
						// 根据item的属性创建fileList_fujian1需要的格式
						name: item.title || `附件${index + 1}`,
						url: item.url || '',
						path: item.url || '',
						type: item.type || '',
						fileType: item.fileType || '',
						size: item.size || 0,
						status: 'success',
						message: '',
						thumb: item.thumb || item.url || '',
						title: item.title || `附件${index + 1}`,
						id: item.id || ''
					}));
				}
			} else {
				//console.log('没有可同步的附件数据');
				// 设置为添加模式
				this.fujian_data_list_cuozuo = 0;
				// 清空fileList_fujian1
				this.fileList_fujian1 = [];
			}
		},
        // 关闭附件列表
        fujian_close_get(){
            // 停止附件播放
            if (this.$refs.audioPlayer) {
                try {
                    //this.$refs.audioPlayer.pause();
                } catch (error) {
                    //console.log('停止附件播放失败:', error);
                }
            }
            this.$emit('fujian_close_get', false);
            // 保留附件数据，避免下次打开时需要重新加载
            //console.log('关闭组件时保留附件数据');
        },
        // 上传附件
		fujian_upload(){
            const duixin = this; // 定义duixin变量指向this
            const uid = this.$store.state.memberuid;
            const keycode = this.$store.state.keycode;
            
            if(!uid || !keycode){
                uni.showToast({
                    icon: 'none',
                    title: '请先登录'
                });
                return;
            }
            
            uni.chooseAudio({
                success: (res) => {
                    // 显示加载中
                    uni.showLoading({
                        title: '上传中...'
                    });
                    var upid = duixin.fabuid && duixin.fabuid.fujianid;
                    // 使用uni.uploadFile上传附件文件
                    uni.uploadFile({
                        url: QuanApi.postTupians(uid,keycode)+'&fid='+upid,
                        filePath: res.tempFilePath,
                        name: 'file_data',
                        formData: {
                            is_ajax: 1
                        },
                        success: (uploadRes) => {
                            try {
                                const data = JSON.parse(uploadRes.data);
                                if(data.code){
                                    // 上传成功，保存返回的附件URL为数组格式
                                    const fujianUrl = data.data.url || '';
                                    // 确保fujian_data_add存在并且有fujian数组
                                    if (!duixin.fujian_data_add) {
                                        duixin.fujian_data_add = {};
                                    }
                                    if (!duixin.fujian_data_add.fujian) {
                                        duixin.fujian_data_add.fujian = [];
                                    }
                                    duixin.fujian_data_add.fujian[0] = fujianUrl;
                                    
                                    uni.showToast({
                                        icon: 'success',
                                        title: '上传成功'
                                    });
                                } else {
                                    uni.showToast({
                                        icon: 'none',
                                        title: data.msg || '上传失败'
                                    });
                                }
                            } catch (error) {
                                uni.showToast({
                                    icon: 'none',
                                    title: '上传失败，请重试'
                                });
                            }
                        },
                        fail: (error) => {
                            //console.log('上传失败:', error);
                            uni.showToast({
                                icon: 'none',
                                title: '上传失败，请重试'
                            });
                        },
                        complete: () => {
                            uni.hideLoading();
                        }
                    });
                },
                fail: (error) => {
                    //console.log('选择附件失败:', error);
                }
            });
        },
        // 附件上传
		async afterRead_fujian(event) {
			const duixin = this; // 定义duixin变量指向this
			// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				//console.log('event',event); 
				let lists = [].concat(event.file)
				let fileListLen = this[`fileList_fujian${event.name}`].length || 0;

				lists.map((item) => {
					// 确保item.type存在，不限制文件类型
					const fileType = item.type || '';
                    this[`fileList_fujian${event.name}`].push({
                    	...item,
                    	status: 'uploading',
                    	message: '上传中',
                    	type: fileType,
                    	// 显式设置fileType为audio，避免组件误判
                    	//fileType: 'audio',
                    	// 确保url属性始终存在，避免传递undefined给image()函数
                    	url: item.url || item.path || '',
                    	// 确保thumb属性始终存在
                    	thumb: item.thumb || item.url || item.path || ''
                    })
                    
				})
				//console.log('上传','123456');
			for (let i = 0; i < lists.length; i++) {
				try {
					const result = await this.uploadFilePromise(lists[i].url, 2)
					// 安全地获取id，防止中间属性不存在
					const id = duixin.up_fujian && duixin.up_fujian.data && duixin.up_fujian.data.id || 0;
					
					let item = this[`fileList_fujian${event.name}`][fileListLen]
					// 更新文件列表状态
						const updatedItem = Object.assign({}, item, {
							status: 'success',
							message: '',
							url: result || '',
							id: id,
							title: '未命名附件' // 添加默认标题
						})
						this[`fileList_fujian${event.name}`].splice(fileListLen, 1, updatedItem)
						fileListLen++
				} catch (error) {
					console.error('处理附件文件时出错:', error);
					// 更新文件列表状态为失败
					let item = this[`fileList_fujian${event.name}`][fileListLen]
					const updatedItem = Object.assign({}, item, {
						status: 'fail',
						message: '上传失败'
					})
					this[`fileList_fujian${event.name}`].splice(fileListLen, 1, updatedItem)
					// 显示失败提示
					uni.showToast({
						icon: 'none',
						title: '上传失败，请重试'
					});
				}
				// 注释掉自动插入逻辑，根据用户需求取消自动插入
				// if (updatedItem.fileType === 'image') {
				// 	this.handleInsertImage({ url: result })
				// } else if (updatedItem.fileType === 'video') {
				// 	this.handleInsertVideo({ url: result })
				// }
				}
		},
		// 删除文件
		delete_fujian(indexOrEvent) {
			// 判断是从附件列表删除还是从上传列表删除
			if (typeof indexOrEvent === 'number') {
				// 从附件列表删除
				if (this.fujian_data_add && this.fujian_data_add.fujian) {
					// 显示确认对话框
					uni.showModal({
						title: '确认删除',
						content: '确定要删除这个附件吗？',
						success: (res) => {
							if (res.confirm) {
								// 获取要删除的附件项
								const deletedItem = this.fujian_data_add.fujian[indexOrEvent];
								// 移除对应的附件
								this.fujian_data_add.fujian.splice(indexOrEvent, 1);
								
								// 同时从fileList_fujian1中删除对应的附件数据
								if (this.fileList_fujian1 && this.fileList_fujian1.length) {
									// 查找fileList_fujian1中对应的数据项
									const fileIndex = this.fileList_fujian1.findIndex(fileItem => {
										// 检查deletedItem是对象还是字符串
										if (typeof deletedItem === 'object') {
											return fileItem.url === deletedItem.url || fileItem.path === deletedItem.url || fileItem.url === deletedItem.path;
										} else if (typeof deletedItem === 'string') {
											return fileItem.url === deletedItem || fileItem.path === deletedItem;
										}
										return false;
									});
									
									// 如果找到了对应的项，从fileList_fujian1中删除
									if (fileIndex !== -1) {
										this.fileList_fujian1.splice(fileIndex, 1);
									}
								}
								
								// 显示删除成功提示
								uni.showToast({
									icon: 'success',
									title: '删除成功'
								});
								// 刷新父组件数据
								this.$emit('refreshData');
								// 调用上传方法同步fileList_fujian1数据
								this.uploadAfterDelete();
							}
						}
					});
				}
			} else {
				// 从上传列表删除
				const fileItem = this[`fileList_fujian${indexOrEvent.name}`][indexOrEvent.index];
				this[`fileList_fujian${indexOrEvent.name}`].splice(indexOrEvent.index, 1);
				
				// 同时从fujian_data_add.fujian中删除对应的附件
				if (this.fujian_data_add && this.fujian_data_add.fujian) {
					// 根据url或其他标识符找到对应的附件项
					const fujianIndex = this.fujian_data_add.fujian.findIndex(item => {
						// 检查item是对象还是字符串
						if (typeof item === 'object') {
							return item.url === fileItem.url || item.path === fileItem.url || item.url === fileItem.path;
						} else if (typeof item === 'string') {
							return item === fileItem.url || item === fileItem.path;
						}
						return false;
					});
					
					// 如果找到了对应的项，从fujian_data_add.fujian中删除
					if (fujianIndex !== -1) {
						this.fujian_data_add.fujian.splice(fujianIndex, 1);
					}
				}
				// 调用上传方法同步fileList_fujian1数据
				this.uploadAfterDelete();
			}
		},
		// 删除附件后上传最新的fileList_fujian1数据
		uploadAfterDelete() {
			const uid = this.$store.state.memberuid;
			const keycode = this.$store.state.keycode;
			const id = this.fabuid && this.fabuid.fujianid;
			
			if (!id) {
				console.log('没有找到发布ID，无法上传附件数据');
				return;
			}
			
			// 上传附件
			let fujian = '';
			var up_fujian = this.fileList_fujian1;
			up_fujian.forEach(item=>{
				fujian+= '&data[fujian][id][]='+item.id+'&data[fujian][title][]='+item.title;
			})
			/*var datas = "is_ajax=1&cid="+id+fujian;
			var post_data = postRequest(QuanApi.getEdit_fujian(uid,keycode,id),datas);
			var res;
			post_data.then(duixin_data => {
				res = duixin_data;
				if(res.data.code) {
					// 刷新父组件数据
					this.$emit('refreshData');
				} else {
					console.log('上传附件数据失败:', res.data.msg);
				}
			}).catch(error => {
				console.error('上传附件数据时发生错误:', error);
			});*/
		},
        		//上传图片
		uploadFilePromise(url,leixing) {
			var duixin = this; 
			const uid = this.$store.state.memberuid;
            const keycode = this.$store.state.keycode;
            var upid = duixin.fabuid && duixin.fabuid.fujianid;
            if(this.fujian_data_add && this.fujian_data_add.fujian && this.fujian_data_add.fujian.length){
                //this.$refs.audioPlayer.pause();
            }
			return new Promise((resolve, reject) => {
				let a = uni.uploadFile({
					url: Api.postTupians(uid,keycode)+'&fid='+upid, //
					filePath: url,
					name: 'file_data',
					formData: {
						is_ajax:1
					},
					success: (res) => {
						var duixin = this; 
                        duixin.up_fujian = JSON.parse(res.data);
                        const fujianUrl = duixin.up_fujian.data.url || '';
                        const id = duixin.up_fujian.data.id || '';
                        if (this.fujian_data_add) {
                        	// 确保fujian属性存在并且是数组
                        	if (!this.fujian_data_add.fujian) {
                        		this.fujian_data_add.fujian = [];
                        	}
                        	// 创建一个包含URL和默认标题的对象，而不是仅仅添加URL字符串
                        	this.fujian_data_add.fujian.push({
                        		url: fujianUrl,
                        		path: fujianUrl,
                        		title: '未命名附件', // 设置默认标题
								id: id || ''
                        		//icon: 'document' // 设置默认图标
                        	});
                        } else {
                        	// 如果fujian_data_add不存在，创建一个新对象
                        	this.fujian_data_add = {
                        		fujian: [{
                        			url: fujianUrl,
                        			path: fujianUrl,
                        			title: '未命名附件', // 设置默认标题
									id: id || ''
                        			//icon: 'document' // 设置默认图标
                        		}]
                        	};
                        }
                        setTimeout(() => {
                        	resolve(fujianUrl)
                        }, 1000)
                    },
                    fail: (error) => {
                        console.error('上传文件失败:', error);
                        reject(error);
                    }
				});
			})
		},
        //发布id
        getFabuid_api(){
        	var duixin = this; 
        	var get_data = getRequest(Api.getFabuid());
        		var res;
        		get_data.then(duixin_data => {
        			res = duixin_data;
        			if(res.data.code) {
        				duixin.fabuid = res.data.data;
        			} else {
        				uni.showToast({
        					icon: 'none',
        					title: '获取失败，请稍后重试'
        				});
        			}
        		})
        },
        //修改
		postfujian_data_xiugai_api(){
			// 确保从 Vuex 获取最新值
			const uid = this.$store.state.memberuid;
			const keycode = this.$store.state.keycode;
			// 确保id存在
			const id = this.tieid || 0;
			
			// 验证附件标题是否为空
			if (this.fujian_data_add && this.fujian_data_add.fujian && this.fujian_data_add.fujian.length > 0) {
				for (let i = 0; i < this.fujian_data_add.fujian.length; i++) {
					const item = this.fujian_data_add.fujian[i];
					// 检查标题是否为空
					if (item && (!item.title || item.title.trim() === '')) {
						uni.showToast({
							icon: 'none',
							title: '请输入附件标题'
						});
						return;
					}
				}
			}
			
			// 上传附件
			let fujian = '';
			var up_fujian = this.fujian_data_add && this.fujian_data_add.fujian;
			up_fujian.forEach(item=>{
				fujian+= '&data[fujian][id][]='+item.id+'&data[fujian][title][]='+item.title;
			})
			var datas = "is_ajax=1&cid="+id+fujian;
			var post_data = postRequest(QuanApi.getEdit_fujian(uid,keycode,id),datas);
			var res;
			post_data.then(duixin_data => {
				res = duixin_data;
				if(res.data.code) {
					uni.showToast({
						icon: 'none',
						title: res.data.msg
					});
					//修改成功后，刷新父组件帖子数据
					this.$emit('refreshData');
					// 操作成功后关闭组件
					this.fujian_close_get();
				} else {
					uni.showToast({
						icon: 'none',
						title: '修改失败'
					});
				}
			})
		},
		// 下载附件
		downloadFile(item) {
			console.log('开始下载文件，item:', item);
			try {
				// 获取文件URL（假设item中包含url或直接是URL）
				const fileUrl = typeof item === 'string' ? item : item.url || '';
				const fileName = typeof item === 'string' ? item.substring(item.lastIndexOf('/') + 1).split('?')[0] : item.title || '下载文件';
				
				if (!fileUrl) {
					uni.showToast({
						icon: 'none',
						title: '文件链接无效'
					});
					return;
				}
				
				// 在H5环境使用a标签下载
				// #ifdef H5
				const link = document.createElement('a');
				link.target = '_blank';
				link.href = fileUrl;
				link.download = fileName;
				link.style.display = 'none';
				document.body.appendChild(link);
				
				const clickEvent = new MouseEvent('click', {
					view: window,
					bubbles: true,
					cancelable: true
				});
				link.dispatchEvent(clickEvent);
				
				setTimeout(() => {
					document.body.removeChild(link);
				}, 100);
				// #else
				// 非H5环境使用uni.downloadFile
				uni.downloadFile({
					url: fileUrl,
					success: (res) => {
						if (res.statusCode === 200) {
							uni.saveFile({
								 tempFilePath: res.tempFilePath,
								 success: (saveRes) => {
									 const savedFilePath = saveRes.savedFilePath;
									 uni.openDocument({
										 filePath: savedFilePath,
										 showMenu: true,
										 success: () => {
											 console.log('文件打开成功');
										 },
										 fail: (err) => {
											 console.log('文件打开失败:', err);
											 uni.showToast({
												 icon: 'none',
												 title: '文件打开失败'
											 });
										 }
									 });
								 },
								 fail: (err) => {
									 console.log('文件保存失败:', err);
									 uni.showToast({
										 icon: 'none',
										 title: '文件保存失败'
									 });
								 }
							});
						}
					},
					fail: (err) => {
						console.log('文件下载失败:', err);
						uni.showToast({
							icon: 'none',
							title: '文件下载失败'
						});
					}
				});
				// #endif
				
				uni.showToast({
					title: '文件开始下载',
					icon: 'success',
					mask: true
				});
			} catch (error) {
				console.log('下载过程中出现错误:', error);
				// 作为最后的备用方案，尝试在新窗口打开
				try {
					const fileUrl = typeof item === 'string' ? item : item.url || '';
					if (fileUrl) {
						window.open(fileUrl, '_blank');
					}
				} catch (browserError) {
					console.log('备用下载方案也失败:', browserError);
					uni.showToast({
						icon: 'none',
						title: '下载失败，请重试'
					});
				}
			}
		},
		// 更新附件标题
		updateFujianTitle(index, newTitle) {
			if (this.fujian_data_add && this.fujian_data_add.fujian && this.fujian_data_add.fujian[index]) {
				// 确保标题不为空
				if (!newTitle || newTitle.trim() === '') {
					// 如果标题为空，设置默认标题
					newTitle = '未命名附件';
					this.fujian_data_add.fujian[index].title = newTitle;
				}
				
				console.log('更新附件标题，索引:', index, '新标题:', newTitle);
				
				// 可以在这里添加自动保存逻辑，或者让用户点击"修改"按钮时一起保存
			}
		}
	}
}
</script>

<style>
.warp_fujian {
	display: flex;
	align-items: center;
	justify-content: center;
	height: 100%;
}
.rect_fujian {
	width: 300px;
	/*height: 300px;*/
	padding: 10px;
	background-color: #fff;
	border-radius: 10px;
}
.d-fujian-gao {
    /*height: 500rpx;*/
    overflow: auto;
}
/* 附件标题输入框样式 */
.fujian-title-input {
    width: 100%;
    padding: 4px 8px;
    /*border: 1px solid #e5e5e5;*/
    border-radius: 4px;
    font-size: 14px;
    outline: none;
}
.fujian-title-input:focus {
    border-color: #007aff;
}
</style>